import {ADD_SEARCH_LOG, CLEAR_SEARCH_LOG} from '../mutationTypes'
import {persistent} from '../plugin/storage'

export default {
  state: {
    @persistent(ADD_SEARCH_LOG, CLEAR_SEARCH_LOG)
    keywords: []
  },
  getters: {
    keywords (state) {
      return state.keywords.sort((a, b) => b.lastModified - a.lastModified).map(it => it.keyword)
    }
  },
  mutations: {
    [ADD_SEARCH_LOG] (state, {keyword}) {
      const {keywords} = state
      const cache = keywords.findIndex(it => it.keyword === keyword)
      const now = Date.now()
      if (cache > -1) {
        keywords[cache].count += 1
        keywords[cache].lastModified = now
      } else {
        keywords.push({keyword, count: 1, lastModified: now})
      }
      state.keywords = keywords
    },
    [CLEAR_SEARCH_LOG] (state) {
      state.keywords = []
    }
  }
}
